package com.yunji.web.common;

import com.yunji.common.base.BaseController;
import com.yunji.common.base.RuoYiConfig;
import com.yunji.common.base.response.Response;
import com.yunji.common.base.response.ResponseHelper;
import com.yunji.common.constant.General;
import com.yunji.common.model.domain.CaptchaPicsDO;
import com.yunji.common.model.enums.UploadType;
import com.yunji.common.model.params.CaptchaPicsParam;
import com.yunji.common.utils.StringUtils;
import com.yunji.common.utils.file.FileUploadUtils;
import com.yunji.common.utils.file.FileUtils;
import com.yunji.system.business.CommonBusiness;
import com.yunji.system.config.ServerConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 通用请求处理
 *
 * @author ruoyi
 */
@Api(tags = "管理端-通用请求处理")
@RestController
@RequestMapping("/common")
public class CommonController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Resource
    private ServerConfig serverConfig;

    @Resource
    CommonBusiness business;

    private static final String FILE_DELIMETER = ",";

    /**
     * @param fileName 文件名称
     * @param delete   是否删除
     * @Title fileDownload
     * @Intro 通用下载请求
     * @Date 2024-06-10 22:28:29.260
     */
    @ApiOperation("通用下载请求")
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (Boolean.TRUE.equals(delete)) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * @param file 文件信息
     * @return Response<Map<String,Object>> 处理结果
     * @Title uploadFile
     * @Intro 通用上传请求(单个)
     * @Date 2024-06-10 22:28:45.192
     */
    @ApiOperation("通用上传请求(单个)")
    @PostMapping("/upload")
    public Response<Map<String,Object>> uploadFile(MultipartFile file) {
        return business.upload(file, UploadType.LOCAL.getCode());
    }

    /**
     * @param file
     * @Title ossUpload
     * @Desc OSS上传文件(单个)
     * @Date 2024-10-15 10:51:55.619
     * @Return Response<Map<String,Object>>
     */
    @ApiOperation("OSS上传文件(单个)")
    @PostMapping("/ossUpload")
    public Response<Map<String,Object>> ossUpload(MultipartFile file) {
        return business.upload(file, UploadType.OSS.getCode());
    }

    /**
     * @param files 文件信息
     * @return Response<Map<String,Object>> 处理结果
     * @Title uploadFiles
     * @Intro 通用上传请求(多个)
     * @Date 2024-06-10 22:29:16.016
     */
    @ApiOperation("通用上传请求(多个)")
    @PostMapping("/uploads")
    public Response<Map<String,Object>> uploadFiles(List<MultipartFile> files) {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<>();
            List<String> fileNames = new ArrayList<>();
            List<String> newFileNames = new ArrayList<>();
            List<String> originalFilenames = new ArrayList<>();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            Map<String, Object> map = new HashMap<>();
            map.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            map.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            map.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            map.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ResponseHelper.success(map);
        } catch (Exception e) {
            return ResponseHelper.failure(e.getMessage());
        }
    }

    /**
     * @param resource 资源信息
     * @Title resourceDownload
     * @Intro 本地资源通用下载
     * @Date 2024-06-10 22:29:35.239
     */
    @ApiOperation("本地资源通用下载")
    @GetMapping("/download/resource")
    public void resourceDownload(String resource) {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, General.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    @ApiOperation("新增滑块验证码")
    @PostMapping("/captcha/create")
    public Response<?> createCaptcha(@RequestBody @Valid CaptchaPicsDO captchaDO) {
        return ResponseHelper.success(business.createCaptcha(captchaDO), "新增成功");
    }

    @ApiOperation("操作状态")
    @PutMapping("/captcha/operate")
    public Response<?> operateCaptcha(@RequestParam("picsId") Long picsId, @RequestParam("status") Integer status) {
        return ResponseHelper.handle(business.operateCaptcha(picsId, status), "操作失败");
    }

    @ApiOperation("编辑")
    @PutMapping("/captcha/edit")
    public Response<?> editCaptcha(@RequestBody CaptchaPicsDO captchaPicsDO) {
        return ResponseHelper.handle(business.editCaptcha(captchaPicsDO), "操作失败");
    }

    @ApiOperation("列表")
    @GetMapping("/captcha/list")
    public Response<?> captchaList(CaptchaPicsParam param) {
        return ResponseHelper.successWithPage(business.captchaList(param));
    }

    @ApiOperation("图片验证码详情")
    @GetMapping("/captcha/getInfo/{picsId}")
    public Response<?> getInfoCaptcha(@PathVariable("picsId") Long picsId) {
        return ResponseHelper.success(business.getInfo(picsId));
    }

    @ApiOperation("批量删除")
    @DeleteMapping("/captcha/delete/{picsIds}")
    public Response<?> deleteCaptcha(@PathVariable List<Long> picsIds) {
        return ResponseHelper.handle(business.delete(picsIds), "删除失败");
    }

}
